package com.tfblog.blog.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tfblog.blog.entity.Blog;
import com.tfblog.blog.entity.Tag;
import com.tfblog.blog.entity.User;
import com.tfblog.blog.service.BlogService;
import com.tfblog.blog.service.UserService;
import com.tfblog.blog.vo.BlogVO;
import com.tfblog.blog.vo.DayCount;
import com.tfblog.blog.vo.TimeVO;
import com.tfblog.exception.CodeException;
import com.tfblog.utils.Msg;
import com.tfblog.utils.PageUtils;
import com.tfblog.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by FengBin on 2021/4/20 19:37
 */
@RefreshScope   //自动刷新配置文件信息注解
@RestController
@RequestMapping("/blogs")
@CrossOrigin
public class BlogController {

    @Autowired
    UserService userService;

    @Autowired
    BlogService blogService;


    /*
    * 分页查询博客内容
    * */
    @GetMapping("/list")
    public R findBlogs(@RequestParam Map<String,Object> params) {
        PageUtils page = blogService.queryPage(params);
        return R.ok().put("page",page);
    }

    /*
    * 根据分类id进行分页查询
    */
    @GetMapping("/info/type/{typeId}")
    public R findBlogsByTypeId(@PathVariable("typeId") Long typeId,@RequestParam Map<String,Object> params) {
        PageUtils page = blogService.queryPageByTypeId(typeId,params);
        return R.ok().put("page",page);
    }

    /*
    * 根据标签id进行分页查询
    * */
    @GetMapping("/info/tag/{tagId}")
    public R findBlogsByTagId(@PathVariable("tagId") Long tagId,@RequestParam Map<String,Object> params) {
        PageUtils page = blogService.queryPageByTag(tagId,params);
        return R.ok().put("page",page);
    }

    /*
    * 根据博客id和分类id/标签id查找对应的博客内容
    * 分类 : 0
    * 标签 : 1
    * */
    @GetMapping("/info/{blogId}/{tId}/{styleId}")
    public R findBlogById(@PathVariable("blogId") Long blogId,@PathVariable Long tId,@PathVariable("styleId") Long styleId) {
        Blog blog = blogService.selectBlogById(blogId,tId,styleId);
        if (blog == null) {
            return R.ok().putStatus(CodeException.NOTFOUND_BLOG.getMsg(),CodeException.NOTFOUND_BLOG.getStatus());
        }
        return R.ok().put("data",blog);
    }

    /*
     * 博客内容的保存 : 如果是保存为草稿,将published字段标注为'1'
     * */
    @Transactional
    @PostMapping("/save")
    public R saveBlog(@RequestBody BlogVO blogVO) {
        Blog blog = new Blog();
        BeanUtils.copyProperties(blogVO,blog);
        //我们添加创建时间(更新时间自动更新)
        //此时我们需要更新两张表 : tf_blog表和tf_blogs_tags表的映射关系
        //第一步 : 我们将blog内容保存到tf_blog表中
        blogService.save(blog);
        //第二步 : 将ty_blog的id和tf_tag的id映射到外键表中去
        Long blogId = blog.getId();
        Long[] tagIds = blogVO.getTags();
        if (tagIds.length != 0) {
            //说明该博客添加了标签
            blogService.saveBlogIdAndTagIds(blogId,tagIds);
        }
        return R.ok().putStatus("博客保存成功",200);
    }

    /*
    * 对于博客内容的修改
    * */
    @Transactional
    @PostMapping("/update")
    public R updateBlog(@RequestBody BlogVO blogVO) {
        Blog blog = new Blog();
        BeanUtils.copyProperties(blogVO,blog);
        //我们添加创建时间(更新时间自动更新)
        //此时我们需要更新两张表 : tf_blog表和tf_blogs_tags表的映射关系
        //第一步 : 我们更新blog内容
        blogService.saveOrUpdate(blog);
        //第二步 : 将ty_blog的id和tf_tag的id重新映射到外键表中去
        Long blogId = blog.getId();
        Long[] tagIds = blogVO.getTags();
        //接着进行外键表的博客id---标签id的维护
        blogService.updateBlogIdAndTagIds(blogId,tagIds);
        return R.ok().putStatus("博客修改成功",200);
    }


    /*
    * 博客内容的删除
    * 因为我们的删除是逻辑删除,故我们在删除的时候,只是博客的逻辑删除标志deleted置为1,对于博客-标签的外键表不用进行维护
    * */
    @Transactional
    @PostMapping("/delete")
    public R deleteBlog(@RequestParam Long id) {
        blogService.deleteBlog(id);
        return R.ok().putStatus("博客删除成功",200);
    }

    /*
     * 根据博客id获取对应的标签信息
     * */
    @GetMapping("/tags/{id}")
    public R findTagsByBlogId(@PathVariable Long id) {
        List<Tag> tagList = blogService.selectTagsByBlogId(id);
        return R.ok().put("data",tagList);
    }

    /*
    * 返回草稿信息: 分页显示
    * */
    @GetMapping("/draft")
    public R queryPageDrafts(@RequestParam Map<String,Object> params) {
        PageUtils page = blogService.qureryPageDraft(params);
        return R.ok().put("page",page);
    }

    /*
    * 分页返回hot热门数据
    * */
    @GetMapping("/hot")
    public R listHotBlogs(@RequestParam Map<String,Object> params) {
        PageUtils page = blogService.queryHotBlogs(params);
        return R.ok().put("page",page);
    }

    /*
    * 根据博客id查询博客详情
    * */
    @GetMapping("/details/{id}")
    public R findDetailsById(@PathVariable("id") Long id) {
        Blog blog = blogService.selectDetailsById(id);
        if (blog == null) {
            return R.ok().putStatus(CodeException.NOTFOUND_BLOG.getMsg(),CodeException.NOTFOUND_BLOG.getStatus());
        }
        //查询博客对应的标签
        List<Tag> tags = blogService.selectTagsByBlogId(id);
        return R.ok().put("data",blog).put("tags",tags);
    }

    /*
    * 获取不同日期(每年每月每日的博客数据)
    * */
    @GetMapping("/time/info")
    public R findTimeInfo(@RequestParam Long year,@RequestParam Long month) {
        List<TimeVO> blogList = blogService.findTimeInfo(year,month);
        if (blogList.size() == 0) {
            //说明该年月下没有博客
            return R.ok().putStatus(CodeException.NOTBLOG_TIME.getMsg(),CodeException.NOTBLOG_TIME.getStatus()).put("count",blogList.size());
        }else {
            return R.ok().put("data",blogList).put("count",blogList.size());
        }
    }

    /*
    * 返回指定年份每一天的博客数量
    * */
    @GetMapping("/time/count")
    public R findEveryDayBlogCount(@RequestParam Long year) {
        List<DayCount> list = blogService.findEveryDayBlogCount(year);
        return R.ok().put("data",list);
    }

    /*
    * 获取最新的博客 : 只获取最新刚发布的十篇
    * */
    @GetMapping("/new")
    public R findNewBlogs() {
        PageUtils page = blogService.queryNewBlogs();
        return R.ok().put("page",page);
    }

    /*
    * 返回现存博客的最小的年份
    * */
    @GetMapping("/minYear")
    public R findMinYear() {
        Long minYear = blogService.findMinYear();
        return R.ok().put("minyear",minYear);
    }

    @Transactional
    @PostMapping("/updateView/{id}")
    public R updateViewsByBlogId(@PathVariable Long id) {
        //根据传入的id查找博客
        Blog blog = blogService.findBlogById(id);
        if (blog != null) {
            Integer views = blog.getViews();
            views += 1;
            blog.setViews(views);
            blogService.updateById(blog); //更新博客
            return R.ok().putStatus("浏览量更新成功",200);
        }else {
            return R.ok().putStatus(CodeException.NOTFOUND_BLOG.getMsg(),CodeException.NOTFOUND_BLOG.getStatus());
        }
    }


}
